﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlyHorse.LIMS.Model;
using FlyHorse.LIMS.WinApp.Utils;
using FlyHorse.LIMS.WinApp.LanguageResource;
using DevExpress.XtraLayout.Utils;

namespace FlyHorse.LIMS.WinApp.DataManageForms.ReportMixForms
{
    public partial class ReportMixDetailForm : DevExpress.XtraEditors.XtraForm
    {
        BLL.GoodBll goodsBll = new BLL.GoodBll();
        BLL.ReportMixBll reportMixBll = new BLL.ReportMixBll();
        BLL.ToolBll toolBll = new BLL.ToolBll();
        int _operation;
        ReportMix _report;
        List<ReportMixResult> _resList;
        Action<IQueryable<ReportMix>> _RefreshGrid;
        OJCB4Entities db = new OJCB4Entities();
        public ReportMixDetailForm(Action<IQueryable<ReportMix>> RefreshGrid)
        {
            InitializeComponent();
            _operation = 1;
            _RefreshGrid = RefreshGrid;
        }
        public ReportMixDetailForm(ReportMix report, Action<IQueryable<ReportMix>> RefreshGrid)
        {
            InitializeComponent();
            _operation = 2;
            _report = db.ReportMixes.Find(report.ReportMixID);
            _RefreshGrid = RefreshGrid;
        }

        private void ReportMixDetailForm_Load(object sender, EventArgs e)
        {
            //绑定 lookUpEditGoodsName 数据
            lookUpEditGoodsName.Properties.DataSource = toolBll.GetSemiGoodList();
            lookUpEdit_SamplingPlaceMixID.Properties.DataSource = toolBll.GetMixSamplingPlaceList();

            if (_operation == 1)
            {
                //this.textEdit_UserName.Text = LoginUserUtil.LoginUser.EmpName;
                this.Text = ResourceOverall.CreateStr;
                //this.textEdit_Environment.Text = "24±2℃/50±5%";
            }

            if (_operation == 2)  //
            {
                this.Text = ResourceOverall.EditStr;
                this.lookUpEditGoodsName.Enabled = false;
                this.lookUpEditGoodsName.EditValue = _report.GoodsID;
                if (_report.SendDate!=null)
                {
                    dateEdit_SendDate.DateTime = Convert.ToDateTime( _report.SendDate);
                }
                else
                {
                    dateEdit_SendDate.EditValue = null;
                }
                if (_report.ProduceDate!=null)
                {
                    dateEdit_ProduceDate.DateTime =Convert.ToDateTime( _report.ProduceDate);
                }
                else
                {
                    dateEdit_ProduceDate.EditValue = null;
                }
                
                lookUpEdit_SamplingPlaceMixID.EditValue = _report.SamplingPlaceMixID;
                textEdit_LotNO.Text = _report.LotNO;
                //textEdit_UserName.Text = _report.LoginUser.UserName;
                textEdit_Conclusion.Text = _report.Conclusion;
                textEdit_Remark.Text = _report.Remark;
                this.textEdit_SendPerson.Text = _report.SampleSendPerson;
                this.textEdit_Factory.Text = _report.Factory;
                this.textEdit_sampleNO.Text = _report.SampleNO;
                this.textEdit_reportNO.Text = _report.ReportNO;
                if (_report.TestDate!=null)
                {
                    this.dateEdit_TestDate.DateTime = Convert.ToDateTime( _report.TestDate);
                }
                this.textEdit_PackingQuantity.Text = _report.PackingQuantity;
                this.textEdit_packingSpecification.Text = _report.packingSpecification;
                this.textEdit_BagQuantity.Text = _report.BagQuantity;
                this.textEdit_SampleQuantity.Text = _report.SampleQuantity;
                this.textEdit_Environment.Text = _report.Environment;

                _resList = _report.ReportMixResults.OrderBy(m=>m.FormOrder).ToList();
                this.dataGridControl.DataSource = _resList;
            }
        }

        private void lookUpEditGoodsName_EditValueChanged(object sender, EventArgs e)
        {
            string goodsID = Convert.ToString(this.lookUpEditGoodsName.EditValue);
            var list = reportMixBll.GetEmptResultList(goodsID);
            _resList = list;
            this.dataGridControl.DataSource = _resList;
        }

        private void ButtonItem_save_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //关闭编辑状态
            this.gridView1.CloseEditor();
            //判空
            if (this.lookUpEditGoodsName.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                this.lookUpEditGoodsName.Focus();
                return;
            }
            if (this.lookUpEdit_SamplingPlaceMixID.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                this.lookUpEdit_SamplingPlaceMixID.Focus();
                return;
            }
            if (dateEdit_TestDate.EditValue==null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                this.dateEdit_TestDate.Focus();
                return;
            }
            if (String.IsNullOrEmpty( this.textEdit_reportNO.Text))
            {
                 XtraMessageBox.Show(ResourceOverall.InputNull);
                 textEdit_reportNO.Focus();
                 return;
            }
    

            if (_operation == 1)
            {
                //int count = db.ReportMixes.AsNoTracking().Where(m => m.ReportNO == this.textEdit_reportNO.Text).Count();
                //if (count>0)
                //{
                //    this.textEdit_reportNO.Focus();
                //    XtraMessageBox.Show("报告编号重复!");
                //    return;
                //}

                ReportMix reportMix = new ReportMix();
                reportMix.ReportMixID = Guid.NewGuid().ToString();
                reportMix.SamplingPlaceMixID = this.lookUpEdit_SamplingPlaceMixID.EditValue.ToString();
                reportMix.Conclusion = this.textEdit_Conclusion.Text;
                reportMix.Remark = this.textEdit_Remark.Text;
                reportMix.LoginUserID = LoginUserUtil.LoginUser.LoginUserID;
                reportMix.AddDateTime = DateTime.Now;
                reportMix.ReportNO = this.textEdit_reportNO.Text;
                reportMix.GoodsID = lookUpEditGoodsName.EditValue.ToString();
                //20170406新增字段
                if (this.dateEdit_TestDate.EditValue != null && dateEdit_TestDate.Text != "")
                {
                    reportMix.TestDate = this.dateEdit_TestDate.DateTime;
                }
                reportMix.SampleSendPerson = this.textEdit_SendPerson.Text;
                if (this.dateEdit_ProduceDate.EditValue != null && dateEdit_ProduceDate.Text != "")
                {
                    reportMix.ProduceDate = this.dateEdit_ProduceDate.DateTime;
                }
                reportMix.PackingQuantity = this.textEdit_PackingQuantity.Text;
                reportMix.packingSpecification = this.textEdit_packingSpecification.Text;
                reportMix.BagQuantity = this.textEdit_BagQuantity.Text;
                reportMix.LotNO = textEdit_LotNO.Text;

                reportMix.SampleNO = this.textEdit_sampleNO.Text;
                reportMix.Factory = this.textEdit_Factory.Text;
                reportMix.SampleQuantity = this.textEdit_SampleQuantity.Text;
                if (this.dateEdit_SendDate.EditValue != null && dateEdit_SendDate.Text != "")
                {
                    reportMix.SendDate = this.dateEdit_SendDate.DateTime;
                }
                reportMix.Environment = this.textEdit_Environment.Text;

                
                reportMix.ReportMixResults = _resList;
                db.ReportMixes.Add(reportMix);
                var res = db.SaveChanges() > 0;
                if (res)
                {
                    var models = reportMixBll.LoadEntitiesAsNoTracking(m => true);
                    _RefreshGrid(models);
                    XtraMessageBox.Show(ResourceOverall.CreateSucceed);
                    this.Close();
                }
            }
            if (_operation == 2)   //_report
            {
                _report.GoodsID = lookUpEditGoodsName.EditValue.ToString();
                _report.SamplingPlaceMixID = this.lookUpEdit_SamplingPlaceMixID.EditValue.ToString();
                if (this.dateEdit_SendDate.EditValue != null && dateEdit_SendDate.Text != "")
                {
                    _report.SendDate = this.dateEdit_SendDate.DateTime;
                }
                if (this.dateEdit_ProduceDate.EditValue != null && dateEdit_ProduceDate.Text != "")
                {
                    _report.ProduceDate = this.dateEdit_ProduceDate.DateTime;
                }
                if (this.dateEdit_TestDate.EditValue != null && dateEdit_TestDate.Text != "")
                {
                    _report.TestDate = this.dateEdit_TestDate.DateTime;
                }


                _report.PackingQuantity = this.textEdit_PackingQuantity.Text;
                _report.packingSpecification = this.textEdit_packingSpecification.Text;
                _report.BagQuantity = this.textEdit_BagQuantity.Text;
                _report.SampleQuantity = this.textEdit_SampleQuantity.Text;
                _report.Environment = this.textEdit_Environment.Text;
                _report.LotNO = textEdit_LotNO.Text;
                _report.Conclusion = this.textEdit_Conclusion.Text;
                _report.Remark = this.textEdit_Remark.Text;
                _report.LoginUserID = LoginUserUtil.LoginUser.LoginUserID;
                _report.SampleSendPerson = this.textEdit_SendPerson.Text;
                _report.Factory = this.textEdit_Factory.Text;
                _report.SampleNO = this.textEdit_sampleNO.Text;
                _report.ReportNO = this.textEdit_reportNO.Text;



                _report.ReportMixResults = this._resList;
                var res = db.SaveChanges() > 0;
                if (res)
                {
                    var models = reportMixBll.LoadEntitiesAsNoTracking(m => true);
                    _RefreshGrid(models);
                    XtraMessageBox.Show(ResourceOverall.EditSucceed);
                    this.Close();
                }
            }
        }

        //private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        //{
        //    //int col = e.ColumnIndex;
        //    //int row = e.RowIndex;
        //    //ReportMixResult result = _resList[row];
        //    //string res = FlyHorse.LIMS.WinApp.Utils.GradeJudging.GetResultByValue(result.MinValue, result.MaxValue, result.TestValue);
        //    //_resList[row].Conclusion = res;
        //    //this.dataGridControl.Refresh();
        //}

        private void ButtonItem_addTestItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.lookUpEditGoodsName.EditValue == null)
            {
                XtraMessageBox.Show("样品名称必选!The name of the sample must be selected !");
                return;
            }
            FlyHorse.LIMS.WinApp.OtherForms.AddResultForm addResultForm = new OtherForms.AddResultForm(AddTestItem);
            addResultForm.ShowDialog();
        }

        private void AddTestItem(TestItem testItem, string minValue, string maxVlaue)
        {
            //查询是否存在重复项目
            foreach (var result in _resList)
            {
                if (result.TestItemID == testItem.TestItemID)
                {
                    XtraMessageBox.Show(ResourceOverall.DataExists);
                    return;
                }
            }
            ReportMixResult res = new ReportMixResult();
            res.Basis = testItem.Basis;
            res.ChineseName = testItem.ChineseName;
            res.FormOrder = testItem.Order;
            res.ReportMixResultID = Guid.NewGuid().ToString();
            res.MinValue = minValue;
            res.MaxValue = maxVlaue;
            res.TestItemID = testItem.TestItemID;
            res.Unit = testItem.Unit;
            _resList.Add(res);
            dataGridControl.RefreshDataSource();
            this.dataGridControl.Refresh();
        }

        private void ButtonItem_DelTestItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.gridView1.GetFocusedRowCellValue("ReportMixResultID") != null)
            {
                DialogResult result = XtraMessageBox.Show(ResourceOverall.ConfirmDelete, ResourceOverall.SystemWarningStr, MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    string id = (string)this.gridView1.GetFocusedRowCellValue("ReportMixResultID");
                    _resList = (List<ReportMixResult>)this.dataGridControl.DataSource;
                    ReportMixResult res = _resList.Where(m => m.ReportMixResultID == id).First();
                    DeleteReportResult(_resList, res);
                    this.dataGridControl.RefreshDataSource();
                }
            }
            else
            {
                XtraMessageBox.Show(ResourceOverall.SelectNull);
            }
        }


        public void DeleteReportResult(List<ReportMixResult> reslutList, ReportMixResult res)
        {
            var entity = db.ReportMixResults.Where(m => m.ReportMixResultID == res.ReportMixResultID).FirstOrDefault();
            if (entity != null)
            {
                db.ReportMixResults.Remove(entity);
                db.SaveChanges();
                reslutList.Remove(res);
            }
            else
            {
                reslutList.Remove(res);
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            string id = (string)this.gridView1.GetRowCellValue(e.RowHandle, "ReportMixResultID");
            string minValue = null;
            string maxValue = null;
            string testValue = null;
            if (this.gridView1.GetRowCellValue(e.RowHandle, "MinValue") != null)
            {
                minValue = this.gridView1.GetRowCellValue(e.RowHandle, "MinValue").ToString();
            }
            if (this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue") != null)
            {
                maxValue = this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue").ToString();
            }
            if (this.gridView1.GetRowCellValue(e.RowHandle, "TestValue") != null)
            {
                testValue = this.gridView1.GetRowCellValue(e.RowHandle, "TestValue").ToString();
            }

            if (!String.IsNullOrEmpty(minValue))
            {
                Convert.ToDouble(this.gridView1.GetRowCellValue(e.RowHandle, "MinValue"));
                minValue = Convert.ToString(this.gridView1.GetRowCellValue(e.RowHandle, "MinValue"));
            }
            if (!String.IsNullOrEmpty(maxValue))
            {
                Convert.ToDouble(this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue"));
                maxValue = Convert.ToString(this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue"));
            }
            if (!String.IsNullOrEmpty(testValue))
            {
                try
                {
                    Convert.ToDouble(this.gridView1.GetRowCellValue(e.RowHandle, "TestValue"));
                    testValue = Convert.ToString(this.gridView1.GetRowCellValue(e.RowHandle, "TestValue"));
                }
                catch (Exception ex)
                {
                    this.gridView1.SetRowCellValue(e.RowHandle, "TestValue", null);
                    XtraMessageBox.Show(ex.Message);
                    return;
                }
            }
            string res = FlyHorse.LIMS.WinApp.Utils.GradeJudging.GetResultByValue(minValue, maxValue, testValue);
            _resList.Where(m => m.ReportMixResultID == id).First().Conclusion = res;
            this.dataGridControl.Refresh();
        }

        private void lookUpEdit_SamplingPlaceMixID_EditValueChanged(object sender, EventArgs e)
        {
            if (lookUpEdit_SamplingPlaceMixID.EditValue!=null)
            {
                string placeID = lookUpEdit_SamplingPlaceMixID.EditValue.ToString();
                if (placeID=="16")
                {
                    layoutControlGroup5.Visibility = LayoutVisibility.Always;
                    layoutControlGroup4.Visibility = LayoutVisibility.Never;
                }
                else if (placeID == "3")
                {
                    layoutControlGroup4.Visibility = LayoutVisibility.Always;
                    layoutControlGroup5.Visibility = LayoutVisibility.Never;
                }
                else
                {
                    layoutControlGroup4.Visibility = LayoutVisibility.Never;
                    layoutControlGroup5.Visibility = LayoutVisibility.Never;
                }
            }
        }
    }
}